const { request } = require('../../utils/request.js');
const api = require('../../utils/api.js');
Page({
  data: {
    currentIndex: 0,
    questions: [],
    errorCount: 0,
    noNext: false,
    // 用于WXML的计算属性，避免复杂表达式
    progressPercent: 5,
    isLastQuestion: false,
    buttonText: '下一题',
    navDots: []
  },

  onLoad() {
    console.log('页面加载');
    this.getQuestions();
  },

  onReady() {
    console.log('页面渲染完成');
    // 确保页面渲染完成后更新计算数据
    if (this.data.questions.length > 0) {
      this.updateComputedData();
    }
  },

  // 更新计算属性，避免WXML中的复杂表达式
  updateComputedData() {
    const { currentIndex, questions } = this.data;

    // 计算进度百分比
    const progressPercent = ((currentIndex + 1) / 20) * 100;

    // 判断是否最后一题
    const isLastQuestion = currentIndex === 19;

    // 按钮文本
    const buttonText = isLastQuestion ? '完成答题' : '下一题';

    // 生成导航点数据
    const navDots = [];
    for (let i = 0; i < 20; i++) {
      let dotClass = '';
      if (questions[i] && questions[i].isCorrect) {
        dotClass = 'correct';
      } else if (questions[i] && questions[i].isWrong) {
        dotClass = 'wrong';
      } else if (i === currentIndex) {
        dotClass = 'current';
      }
      navDots.push({ class: dotClass });
    }

    // 为当前问题生成选项状态
    const currentQ = questions[currentIndex] || {};
    const optionStates = {
      // 判断题
      isYSelected: currentQ.selectedAnswer === 'Y',
      isNSelected: currentQ.selectedAnswer === 'N',
      isYChecked: currentQ.selectedAnswer === 'Y',
      isNChecked: currentQ.selectedAnswer === 'N',

      // 单选题
      isA1Selected: currentQ.selectedAnswer === '1',
      isB2Selected: currentQ.selectedAnswer === '2',
      isC3Selected: currentQ.selectedAnswer === '3',
      isD4Selected: currentQ.selectedAnswer === '4',
      isA1Checked: currentQ.selectedAnswer === '1',
      isB2Checked: currentQ.selectedAnswer === '2',
      isC3Checked: currentQ.selectedAnswer === '3',
      isD4Checked: currentQ.selectedAnswer === '4',

      // 多选题
      isAMultiSelected: currentQ.selectedA,
      isBMultiSelected: currentQ.selectedB,
      isCMultiSelected: currentQ.selectedC,
      isDMultiSelected: currentQ.selectedD,
      isAMultiChecked: currentQ.selectedA,
      isBMultiChecked: currentQ.selectedB,
      isCMultiChecked: currentQ.selectedC,
      isDMultiChecked: currentQ.selectedD
    };

    this.setData({
      progressPercent,
      isLastQuestion,
      buttonText,
      navDots,
      ...optionStates
    });
  },
  onShow: function () {
    // this.countInterval() //调用
  },

  // 获取题目数据
  getQuestions() {
    wx.showLoading({ title: '加载中...' });
    request(api.get_questions, 'POST', { user_id: wx.getStorageSync('userId') })
      .then(res => {
        const questions = res.data.questions.map(q => ({
          ...q,
          selectedAnswers: [], // 多选题用数组存储
          selectedAnswer: '', // 单选题和判断题
          // 为多选题添加每个选项的选中状态
          selectedA: false,
          selectedB: false,
          selectedC: false,
          selectedD: false,
          hasSelected: false,
          isCorrect: false,
          isWrong: false
        }));

        this.setData({ questions });
        this.updateComputedData();
      })
      .catch(err => {
        console.error('获取失败', err);
      }).finally(res => {
        wx.hideLoading()
      });
  },

  // 选择答案
  selectOption(e) {
    console.log('selectOption 被调用', e);
    const { option } = e.currentTarget.dataset;
    console.log('选择的选项:', option);
    const { currentIndex, questions } = this.data;
    console.log('当前题目索引:', currentIndex, '题目数量:', questions.length);

    if (!questions || !questions[currentIndex]) {
      console.error('当前题目不存在');
      return;
    }

    const currentQuestion = questions[currentIndex];
    console.log('当前题目:', currentQuestion);

    // 获取选项对应的序号（1,2,3,4）
    const optionIndex = option.charCodeAt(0) - 64; // A=>1, B=>2, C=>3, D=>4
    // 更新选中状态
    const key = `selected${option}`;
    console.log('更新选中状态，key:', key);

    if (currentQuestion.type_text === "多选题") {
      currentQuestion[key] = !currentQuestion[key];
      console.log('多选题，更新后状态:', currentQuestion[key]);
      // 多选题处理
      if (!Array.isArray(currentQuestion.selectedAnswers)) {
        currentQuestion.selectedAnswers = [];
      }
      // 更新选中的答案数组
      if (currentQuestion[key]) {
        if (!currentQuestion.selectedAnswers.includes(optionIndex.toString())) {
          currentQuestion.selectedAnswers.push(optionIndex.toString());
        }
      } else {
        const index = currentQuestion.selectedAnswers.indexOf(optionIndex.toString());
        if (index !== -1) {
          currentQuestion.selectedAnswers.splice(index, 1);
        }
      }

      // 排序
      currentQuestion.selectedAnswers.sort((a, b) => a - b);

      // 更新是否有选中的选项
      currentQuestion.hasSelected = currentQuestion.selectedAnswers.length > 0;

      this.setData({
        [`questions[${currentIndex}]`]: currentQuestion
      });
      console.log('多选题setData完成');
    } else if (currentQuestion.type_text === "判断题") {
      // 判断题处理
      currentQuestion.selectedAnswer = option; // Y或N
      console.log('判断题，选择答案:', option);
      this.setData({
        [`questions[${currentIndex}]`]: currentQuestion
      });
      console.log('判断题setData完成');
    } else {
      // 单选题处理
      currentQuestion.selectedAnswer = optionIndex.toString();
      console.log('单选题，选择答案:', optionIndex.toString());
      this.setData({
        [`questions[${currentIndex}]`]: currentQuestion
      });
      console.log('单选题setData完成');
    }
  },
  previewImage() {
    const currentQuestion = this.data.questions[this.data.currentIndex];
    if (currentQuestion.imgUrl) {
      wx.previewImage({
        current: currentQuestion.imgUrl,
        urls: [currentQuestion.imgUrl]
      });
    }
  },
  // 确认多选题答案
  confirmMultiAnswer() {
    const { currentIndex, questions } = this.data;
    const currentQuestion = questions[currentIndex];

    if (!currentQuestion.selectedAnswers || currentQuestion.selectedAnswers.length === 0) {
      wx.showToast({
        title: '请选择答案',
        icon: 'none'
      });
      return;
    }

    this.checkAnswer(currentQuestion);

    // 更新整个questions数组，确保导航状态更新
    this.setData({
      questions: this.data.questions
    });
  },
  // 检查答案
  checkAnswer() {
    let isCorrect = false;
    let nonext = this.data.noNext
    if (nonext) return
    const { currentIndex, questions } = this.data;
    const question = questions[currentIndex]
    if (question.type_text === "多选题") {
      // 多选题答案比对
      const correctAnswers = question.answer.split(',').map(String);
      isCorrect = correctAnswers.length === question.selectedAnswers.length &&
        correctAnswers.every(ans => question.selectedAnswers.includes(ans));
    } else if (question.type_text === "判断题") {
      // 判断题答案比对
      isCorrect = (question.answer === "1" && question.selectedAnswer === "Y") ||
        (question.answer === "2" && question.selectedAnswer === "N");
    } else {
      // 单选题答案比对
      isCorrect = question.answer === question.selectedAnswer;
    }

    question.isCorrect = isCorrect;
    question.isWrong = !isCorrect;
    if (!isCorrect) {
      this.setData({
        errorCount: (this.data.errorCount || 0) + 1
      });

      if (this.data.errorCount > 2) {
        this.examFailed();
        return;
      }
    }
    this.setData({
      [`questions[${currentIndex}]`]: question,
      noNext: true
    });
    this.updateComputedData();
    setTimeout(() => this.nextQuestions(), 500);
  },
  // 下一题
  nextQuestions() {
    const { currentIndex, questions } = this.data;
    if (currentIndex < questions.length - 1) {
      this.setData({
        currentIndex: currentIndex + 1
      });
      this.updateComputedData();
    } else {
      this.examPassed();
    }
    this.setData({
      noNext: false
    });
  },

  // 上一题
  prevQuestion() {
    const { currentIndex } = this.data;
    if (currentIndex > 0) {
      this.setData({
        currentIndex: currentIndex - 1
      });
      this.updateComputedData();
    }
  },
  // 考试失败
  examFailed() {
    wx.showModal({
      title: '考试未通过',
      content: '错误题目已超过2题',
      showCancel: false,
      success: () => {
        wx.navigateBack();
      }
    });
  },
  // 考试通过
  examPassed() {
    const score = this.calculateScore();
    wx.showModal({
      title: '考试完成',
      content: `得分：${score}分\n错误：${this.data.errorCount || 0}题`,
      showCancel: false,
      success: () => {
        wx.navigateBack();
      }
    });
  },

  // 计算得分
  calculateScore() {
    const correctCount = this.data.questions.filter(q => q.isCorrect).length;
    return Math.round((correctCount / this.data.questions.length) * 100);
  },

  onUnload() {
    // 清理资源
  }

});